import {
  getCustomerTable
} from '../../api/customer'
import {
  sendSmsRecord
} from '../../api/sms'
import {
  SMS_SEND_LIST,
  SMS_SEND_DATA_COUNT,
  SMS_SEND_HISTORY_DATA,
  SMS_SEND_PAGE_SIZE
} from '../motations-type'

export default {
  state: {
    smsSendList: [],
    smsSendDataCount: null,
    smsSendPageSize: 20,
    smsSendHistoryData: [],
    row: {
      ctime: '',
      mname: '',
      uname: '',
      tel: '',
      state0: '',
      state: '',
      cprice: ''
    }
  },
  getters: {
    smsSendList: state => state.smsSendList
  },
  mutations: {
    [SMS_SEND_LIST] (state, data) {
      state.smsSendList = data
    },
    [SMS_SEND_DATA_COUNT] (state, data) {
      state.smsSendDataCount = data
    },
    [SMS_SEND_HISTORY_DATA] (state, data) {
      state.smsSendHistoryData = data
    },
    [SMS_SEND_PAGE_SIZE] (state, data) {
      state.smsSendPageSize = data
    }
  },
  actions: {
    async getSmsSendList ({ commit, rootState }, playload) {
      let data = {}
      let newData = []
      if (Object.keys(playload).length > 0) {
        data = playload
      }
      const resp = await getCustomerTable(data)
      resp.data.data.rows.map((item, index) => {
        newData = [...newData, {
          id: item.id,
          ctime: item.ctime,
          mname: item.mname,
          uname: item.uname,
          tel: item.tel,
          state0: item.state0,
          state: item.state,
          cprice: item.cprice,
          index: index,
          _checked: false
        }]
      })
      commit(SMS_SEND_LIST, newData)
      commit(SMS_SEND_DATA_COUNT, resp.data.data.total)
      if (newData.length < rootState.smsSend.smsSendPageSize) {
        commit(SMS_SEND_HISTORY_DATA, newData)
      } else {
        commit(SMS_SEND_HISTORY_DATA, newData.slice(0, rootState.smsSend.smsSendPageSize))
      }
      return resp
    },
    async sendSmsSendData ({ commit, rootState }, playload) {
      let data = {}
      if (Object.keys(playload).length > 0) {
        data = playload
      }
      const resp = await sendSmsRecord(data)
      return resp
    },
    async changeSmsSendPage ({ commit, rootState }, index) {
      let data = rootState.smsSend.smsSendList
      let _start = (index - 1) * rootState.smsSend.smsSendPageSize
      let _end = index * rootState.smsSend.smsSendPageSize
      commit(SMS_SEND_HISTORY_DATA, data.slice(_start, _end))
    },
    async changeSmsSendPageSize ({ commit, rootState }, value) {
      commit(SMS_SEND_PAGE_SIZE, value)
    }
  }
}
